#include "HTTPResponse.h"
#include "ReadFileAction.h"
#include "Application.h"
#include "LuaAction.h"

CHTTPResponse::CHTTPResponse(void)
{

}


CHTTPResponse::~CHTTPResponse(void)
{

}

//TODO Get POST data if request is POST
//TODO Get Errors working!

bool CHTTPResponse::PrepareResponse()
{
	mResponseHeaders += pair<string, string>("Server", "LuaHTTP 0.5");
	mResponseHeaders += pair<string, string>("Connection", "close");
	if(mRequestInfo->mMethod == "GET" || mRequestInfo->mMethod == "POST")
	{
		size_t Pos = mRequestInfo->mResource.find(".");
		if(Pos == string::npos)
		{
			//ERROR Malformed URL? Maybe 404 Could also just be a file upload.
			return false;
		}
		string Mime = CApplication::Configuration.LookupFileMime(mRequestInfo->mResource.substr(mRequestInfo->mResource.find_last_of(".")));
		if(Mime == "Dynamic")
		{
			//cout << "Requested dynamic file" << endl;
			mResponseHeaders += pair<string, string>("Transfer-Encoding", "chunked");
			CScriptInteraction *executionEnv = new CScriptInteraction(mClient, mRequestInfo, &mResponseHeaders);
			mAction = new CLuaAction(executionEnv);
		}
		else
		{
			mResponseHeaders += pair<string, string>("Content-Type", Mime);
			mAction = new CReadFileAction(mClient, mRequestInfo, &mResponseHeaders);
		}
	}
	else
	{
		mResponseHeaders.SetResponseCode(501, "Not Implemented", mRequestInfo->mVersion);
		return false;
	}

	char Time[32];
	time_t rawtime;
	time( &rawtime);
	strftime(Time, 31, "%a, %d %b %Y %X GMT", gmtime(&rawtime));
	mResponseHeaders += pair<string, string>("Date", Time);

	mAction->PrepareAction();
	return true;
}

bool CHTTPResponse::ExecuteResponse()
{
	// Since this is just a read file action we can just output the headers directly

	mAction->ExecuteAction();
	return true;
}
bool CHTTPResponse::CleanUp()
{
	
	mAction->CleanUp();
	mClient->mSocket->Close();
	delete mAction;
	return true;
}